<template>
	<view class="container bg-white" >
		<!-- 标题栏 -->
		<cu-custom :cuCustomTop="15" ref="cuCustom"
			:contentClass="'cu-custom-content-gradient-bg'"
			:isBack="true"
		>
			<block slot="content">
				登录
			</block>
			
		</cu-custom>
		<!-- 内容区 -->
		<view class="container-main" >
			<image class="main-header" src="/static/login_bg.png" mode="aspectFit"></image>
			<view class="main-login">
				<view class="login-title">小程序需要登录注册才能使用相关功能，申请获取以下权限</view>
				<view class="login-subtitle">获得你的公开信息(昵称、头像、手机号码等)</view>
				<!-- 授权登录 -->
				<view class="login-info" v-if="isRegister">
					<view class="info-btn" @click="handleLogin">授权登录</view>
					<view class="info-btn cancel" @click="goBack">暂不登录</view>
				</view>
				<!-- 授权手机号 -->
			<!-- 	<view class="login-info" v-else-if="!phoneNumber">
					<button class="info-btn" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">授权手机号</button>
					<view class="info-btn cancel" @click="goBack">暂不授权</view>
				</view> -->
				<!-- 授权头像昵称 -->
				<form class="login-info" @submit="handleLogin" v-else>
					<view class="info-item">
						<view class="item-title">头像</view>
						<button class="item-avatar" open-type="chooseAvatar" @chooseavatar="bindChooseAvatar">
							<image class="image" :src="avatarPath || '/static/login.png'" mode="aspectFill"></image>
						</button>
					</view>
					<view class="info-item">
						<view class="item-title">昵称</view>
						<input class="item-nickname" type="nickname" name="nickname" :value="userInfo.nickname" placeholder="请输入昵称" />
					</view>
					<button class="info-btn" style="margin-top: 48rpx;" form-type="submit">授权登录</button>
					<button class="info-btn cancel" style="border: unset;" @click="loginEvent">稍后授权</button>
				</form>
			</view>
			
		</view>
	</view>
</template>
<script>
	import {mapState} from "vuex"
	import request from "@/utils/request.js";
	import {uploadFile} from "@/libs/uniApi.js"
	export default {
		data() {
			return {
				// 是否已经注册
				isRegister: false,
				// 已授权手机号
				phoneNumber: null,
				// 已选择头像
				avatarPath: "",
				// 用户信息
				userInfo: {
					avatar: "",
					nickname: "",
				},
			}
		},
		onLoad() {
			// uni.showLoading({
			// 	title: "加载中"
			// })
			this.getAuthStatus(() => {
				uni.hideLoading()
				this.loadEnd = true
			})
		
		},
		onUnload() {
			clearInterval(this.interval)
		},
		computed: {
			...mapState({
				token: state => state.user.token,
			})
		},
		methods: {
			// 返回上一页
			goBack() {
				let pages = getCurrentPages()
				if (pages.length == 1) {
					uni.switchTab({
						url: "/pages/life/index"
					})
				} else {
					if (pages[pages - 1] == 'pages/login/index') {
						uni.navigateBack({
							delta: 2
						})
					} else uni.navigateBack()
				}
			},
			// 微信登录
			// #ifdef MP-WEIXIN
			// 获取账号是否已注册
			getAuthStatus(fn) {
				uni.login({
					provider: 'weixin',
					success: loginRes => {
						request.post("mini/auth/checkWxRegister", {code:loginRes.code}, {
							noAuth: true
						}).then(res => {
							if (res.code == 200) {
								this.isRegister = res.data.is_register;
								return;
							}
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}).catch(err => {
							uni.hideLoading();
							uni.showToast({
								title: err,
								icon: 'none'
							})
							console.error('登录/注册 ', err)
						});
					}
				})
			},
		
			// 选择头像
			bindChooseAvatar(e) {
				uploadFile(e.detail.avatarUrl).then(result => {
					this.userInfo.avatar = result.data.hash
					this.avatarPath = e.detail.avatarUrl
				}).catch(error => {
					console.error('上传图片 ', error)
				})
			},
			// 提交登录
			handleLogin(e) {
				if (!this.isRegister) {
					this.userInfo.nickname = e.detail.value.nickname
					if (!this.avatarPath) {
						uni.showToast({
							title: "请设置头像后登录",
							icon: 'none',
						})
						return
					}
					if (!this.userInfo.nickname) {
						uni.showToast({
							title: "请设置昵称后登录",
							icon: 'none',
						})
						return
					}
				}
				uni.showLoading({
					title: '授权中',
					mask: true,
				})
				
				console.log(this.userInfo);
				this.loginEvent()
			},
			// 提交事件
			loginEvent(mobile) {
				const app = getApp();
				uni.login({
					provider: 'weixin',
					success: loginRes => {
						let data = {
							code: loginRes.code
						}
						if (uni.getStorageSync("parentWechatId")) data.parent_wechat_id = uni.getStorageSync("parentWechatId")
						if (this.userInfo.nickname) data.nickname = this.userInfo.nickname
						if (this.userInfo.avatar) data.avatar = this.userInfo.avatar
						if(app.globalData.code) data.sence =  app.globalData.code
						if(app.globalData.pid) data.parentId = app.globalData.pid
						
						request.post("mini/auth/wxLogin", data, {
							noAuth: true
						}).then(res => {
							uni.hideLoading();
							
							if (res.code == 200) {
								uni.setStorageSync('token', res.data.token);
								uni.setStorageSync("userInfo", res.data)
								this.$store.commit('user/setToken', res.data.token)
								this.$store.commit('user/setUserInfo', res.data)
								this.goBack()
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}
						}).catch(err => {
							uni.hideLoading();
							uni.showToast({
								title: err,
								icon: 'none'
							})
							console.error('登录/注册 ', err)
						});
					},
					fail: () => {
						uni.showToast({
							icon: "none",
							title: "授权失败，请重试"
						})
					}
				})
			},
			// 稍后授权
			laterAuthorize() {
				uni.showLoading({
					title: '授权中',
					mask: true,
				})
				this.loginEvent()
			},
			// #endif
		
		}
	}
</script>
<style lang="scss">
	page {
		background: #fff !important;
	}

	.container {
		.container-main {
			padding: 96rpx 60rpx 0;

			.main-header {
				width: 100%;
				height: 500rpx;
			}

			.main-login {
				margin-top: 76rpx;

				.login-title {
					color: #585858;
					font-size: 34rpx;
				}

				.login-subtitle {
					color: #888;
					font-size: 28rpx;
					margin-top: 40rpx;
				}

				.login-info {
					margin-top: 48rpx;

					.info-item {
						display: flex;
						align-items: center;
						background: #ffffff;
						border-bottom: 1rpx solid #F6F7FB;

						.item-title {
							margin-right: 40rpx;
							font-size: 28rpx;
							line-height: 40rpx;
							color: #000000;
						}

						.item-avatar {
							flex: 1;
							padding: 32rpx 0;
							height: 80rpx;
							background: transparent;
							box-sizing: content-box;
							display: flex;
							justify-content: flex-start;

							&::after {
								border: none;
							}

							.image {
								width: 80rpx;
								height: 80rpx;
								border-radius: 50%;
							}
						}

						.item-nickname {
							flex: 1;
							font-size: 28rpx;
							line-height: 40rpx;
							padding: 32rpx 0;
							box-sizing: content-box;
						}
					}

					.info-btn {
						height: 88rpx;
						line-height: 88rpx;
						font-size: 28rpx;
						border-radius: 16rpx;
						text-align: center;
						background: $--theme-color;
						color: #ffffff;

						&.cancel {
							background: #eee;
							color: #999;
							margin-top: 24rpx;
						}
					}
				}
			}

			.main-form {
				margin-top: 96rpx;

				.form-input {
					border-radius: 16rpx;
					border: 1rpx solid #F0F0F0;
					background: #FFF;
					margin-top: 32rpx;

					&:first-child {
						margin-top: 0;
					}

					.input {
						color: #5A5B6E;
						font-size: 28rpx;
						line-height: 40rpx;
						padding: 36rpx 32rpx;
					}

					.placeholder {
						color: #ACADB7;
					}

					.btn {
						padding: 0 24rpx;
						color: var(--theme-color);
						font-size: 28rpx;
						line-height: 40rpx;
					}

					.countdown {
						padding: 0 24rpx;
						color: #666;
						font-size: 28rpx;
						line-height: 40rpx;
					}
				}

				.form-btn {
					color: #FFF;
					font-size: 28rpx;
					line-height: 40rpx;
					padding: 36rpx;
					border-radius: 16rpx;
					background: var(--theme-color);
					margin-top: 48rpx;
					text-align: center;
				}

				.form-read {
					margin-top: 52rpx;

					.radio {
						width: 32rpx;
						height: 32rpx;
						background: #D6DBDE;
						border-radius: 50%;

						&.active {
							background: var(--theme-color);
						}
					}

					.label {
						margin-left: 20rpx;
						color: #5A5B6E;
						font-size: 24rpx;
						line-height: 34rpx;

						text {
							color: var(--theme-color);
						}
					}
				}
			}
		}
	}
</style>